package com.yuzf.netty.example.nio.filecopy;

import java.io.*;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NioFileCopy implements FileCopy {
    @Override
    public void copy(File source, File target) {
        try (
                FileChannel in = new FileInputStream(source).getChannel();
                FileChannel out = new FileOutputStream(target).getChannel();
        ){
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while(in.read(buffer) != -1){
                buffer.flip();
                while (buffer.hasRemaining()){
                    out.write(buffer);
                }
                buffer.clear();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        NioFileCopy nfc = new NioFileCopy();
        File source = new File("E:\\demo.txt");
        File target = new File("E:\\test\\copy.txt");
        if(!target.exists()){
            try {
                target.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        nfc.copy(source, target);
    }
}
